package com.sakura.apigateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *@ClassName AccessFilter
 *@Description: 过滤出安全的请求
 *@AUthor Sakura
 *@Date 2021/4/27 16:27
 *Version 0.1
 **/
@Slf4j
@Component
public class AccessFilter implements GlobalFilter, Ordered {
    /**
     * url匹配器
     */
    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 拦截器的执行顺序，更改了以后需要重启服务才能生效，最优的返回值为负数不会出现其他问题
     *
     * @return
     */
    @Override
    public int getOrder() {
        // TODO Auto-generated method stub
        return -1000;
    }
    /**
     * 拦截器，处理业务逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("AccessFilter拦截器,获取到请求的URI：{},请求时间：{}", exchange.getRequest().getPath().value(),new SimpleDateFormat(DATE_TIME_PATTERN).format(new Date()));
        /*设置响应头信息**/
        ServerHttpResponse response=exchange.getResponse();
        HttpHeaders httpHeaders=response.getHeaders();
        /*max-age=<expire-time>以秒为单位，浏览器应该记住，该站点只能通过 HTTPS 访问.7776000=90天*/
        httpHeaders.add("Strict-Transport-Security", "max-age=7776000");
        httpHeaders.add("Referer-Policy", "no-referrer");
        httpHeaders.add("Content-Security-Policy", "default-src 'self'");
        httpHeaders.add("X-Permitted-Cross-Domain-Policies", "value");
        httpHeaders.add("X-XSS-Protection", "1; mode=block");
        httpHeaders.add("X-Download-Options", "master-only");
        httpHeaders.add("X-Content-Type-Options", "nosniff");
        return chain.filter(exchange);
    }
}
